﻿using System.Collections.Generic;
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 计算RectTransfom 子节点的总大小
    /// </summary>
    public class CalRectTranformSize : MonoBehaviour
    {
        public float width = 0;
        public float height = 0;
        public bool isSizeWidth = false;
        public bool isSizeHeight = false;

        //[Tooltip("计算空隙节点顺序是从左到右")]
        //public bool isCalInterspace = false;

        public bool isEnableCal;
        
        public List<RectTransform> calRect = new List<RectTransform>();
        
        private void OnEnable()
        {
            if (isEnableCal)
            {
                CalSize();
            }
        }

        public void CalSize()
        {
            RectTransform rt = null;
            width = 0;
            height = 0;
            if (calRect.Count > 0)
            {
                for (int i = 0; i < calRect.Count; i++)
                {
                    rt = calRect[i] as RectTransform;
                    if (isSizeWidth)
                    {
                        width += rt.sizeDelta.x;
                    }
                    if (isSizeHeight)
                    {
                        height += rt.sizeDelta.y;
                    }
                }
            }
            else
            {
                int count = transform.childCount;
                
                for (int i = 0; i < count; i++)
                {
                    rt = transform.GetChild(i) as RectTransform;
                    if (isSizeWidth)
                    {
                        width += rt.sizeDelta.x;
                    }

                    if (isSizeHeight)
                    {
                        height += rt.sizeDelta.y;
                    }
                }
            }



            rt = transform as RectTransform;
            if (isSizeWidth && isSizeHeight)
            {
                rt.sizeDelta = new Vector2(width, height);
            }
            else if (isSizeWidth)
            {
                rt.sizeDelta = new Vector2(width, rt.sizeDelta.y);
            }
            else if (isSizeHeight)
            {
                rt.sizeDelta = new Vector2(rt.sizeDelta.x, height);
            }
        }
    }
}